<template>
  <el-dialog
    :title="way == 0 ? '新增参数' : '修改参数'"
    :visible.sync="visible"
    width="800px"
    append-to-body
    :before-close="handleClose"
  >
    <el-row>
      <el-col :span="24">
        <el-form
          ref="detailform"
          :model="form"
          :rules="rules"
          label-width="120px"
        >
          <el-row v-if="waytype == 4">
            <el-col :span="24">
              <el-form-item label="所属能耗类型" prop="energyType">
                <el-select
                  v-model="form.energyType"
                  size="small"
                  placeholder="请选择能耗类型"
                  @change="getTypeAndLabelLv2Code"
                >
                  <el-option
                    v-for="dict in dict.type.energy_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="Number(dict.value)"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item :label="tabName + '类别'" prop="itemType">
                <el-select
                  v-if="waytype == 4"
                  v-model="form.itemType"
                  size="small"
                  placeholder="请选择能耗类型"
                  :disabled="!String(form.energyType)"
                  clearable
                  @change="(val) => handleSelect(val, 'itemType')"
                >
                  <el-option
                    v-for="dict in live2Codes"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="Number(dict.dictValue)"
                  />
                </el-select>
                <DictionariesSelect
                  v-else
                  :showType="0"
                  :datas="form.itemType"
                  :modelBinding="'itemType'"
                  :selectArr="dictArr"
                  :inputWidth="194"
                  :placeholder="'请选择' + tabName + '类别'"
                  size="small"
                  @handleSelect="(val) => handleSelect(val, 'itemType')"
                ></DictionariesSelect>
                <!-- :clearable="true" -->
                <!-- @handleClear="handleClear" -->
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="waytype == 2">
            <el-col :span="24">
              <el-form-item :label="tabName + '子类'" prop="subitemType">
                <el-select
                  v-model="form.subitemType"
                  size="small"
                  :placeholder="'请选择' + tabName + '子类'"
                  :disabled="!String(form.itemType)"
                  clearable
                  @change="(val) => handleSelect(val, 'subitemType')"
                >
                  <el-option
                    v-for="dict in live2Codes"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="Number(dict.dictValue)"
                  />
                </el-select>
                <!-- <DictionariesSelect
                  :showType="0"
                  :datas="form.subitemType"
                  :modelBinding="'subitemType'"
                  :selectArr="dictArr2"
                  :inputWidth="194"
                  :placeholder="'请选择' + tabName + '子类'"
                  size="small"
                  @handleSelect="handleSelect"
                ></DictionariesSelect> -->
                <!-- :clearable="true" -->
                <!-- @handleClear="handleClear" -->
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item :label="tabName + '规则'" prop="list">
                <div>
                  <el-row>
                    <el-col :span="1" :offset="22">
                      <el-button
                        icon="el-icon-plus"
                        type="text"
                        @click="handleAddrow"
                      >
                        新增
                      </el-button>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="24">
                      <el-table :data="form.list" max-height="415">
                        <el-table-column
                          type="index"
                          label="序号"
                          align="center"
                          width="60"
                        >
                        </el-table-column>
                        <el-table-column
                          prop="relation"
                          label="关系"
                          align="center"
                          width="110"
                        >
                          <template slot-scope="scope">
                            <el-form-item
                              :prop="'list.' + scope.$index + '.relation'"
                              :rules="rules.relation"
                              class="cellCenter"
                            >
                              <el-select
                                size="small"
                                v-model="scope.row.relation"
                                placeholder="关系"
                              >
                                <el-option
                                  v-for="(item, index) in dict.type
                                    .energy_andnorgate"
                                  :key="index"
                                  :label="item.label"
                                  :value="item.value"
                                ></el-option>
                              </el-select>
                            </el-form-item>
                          </template>
                        </el-table-column>
                        <el-table-column
                          prop="ruleId"
                          label="划分规则"
                          align="center"
                          width="320"
                        >
                          <template slot-scope="scope">
                            <el-form-item
                              :prop="'list.' + scope.$index + '.ruleId'"
                              :rules="rules.ruleId"
                              class="cellCenter"
                            >
                              <el-select
                                size="small"
                                v-model="scope.row.ruleId"
                                @change="
                                  handleChange(scope.row.ruleId, scope.$index)
                                "
                                placeholder="规则"
                                style="width: 270px"
                              >
                                <el-option
                                  v-for="(item, index) in rulesArr"
                                  :key="index"
                                  :label="item.ruleContent"
                                  :value="item.ruleId"
                                ></el-option>
                              </el-select>
                            </el-form-item>
                          </template>
                        </el-table-column>
                        <el-table-column
                          fixed="right"
                          label="操作"
                          align="center"
                          class-name="small-padding fixed-width"
                        >
                          <template slot-scope="scope">
                            <el-button
                              size="small"
                              type="text"
                              icon="el-icon-delete"
                              @click="handleDelete(scope.row)"
                              style="color: #f56c6c"
                            >
                              删除
                            </el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                    </el-col>
                  </el-row>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="是否单独计量" prop="measureAlone">
                <el-radio-group v-model="form.measureAlone">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- <el-row>
            <el-col :span="24">
              <el-form-item label="创建时间" prop="date">
                <el-date-picker
                  v-model="form.date"
                  type="datetime"
                  placeholder="选择日期时间"
                  :picker-options="pickerOptions"
                  value-format="timestamp"
                  size="small"
                  style="width: 194px"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row> -->
          <!-- <el-row>
            <el-col :span="24">
              <el-form-item label="创建人员" prop="people">
                <el-input
                  v-model="form.people"
                  size="small"
                  style="width: 194px"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row> -->
        </el-form>
      </el-col>
    </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" type="primary" @click="handleConfirm">
        确定
      </el-button>
      <el-button size="small" @click="handleClose">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getDetail, getRuleslist, postSub, putSub } from "@/api/sub/manage";
import { typeAndLabelLv2Code } from "@/api/system/dict/data";
import { deepClone } from "@/utils/index";
import DictionariesSelect from "@/components/DictionariesSelect/index.vue";
export default {
  props: {
    visible: { type: Boolean, default: false, require: true },
    id: { type: [String, Number], default: 0, require: true },
    waytype: { type: String, default: "1", require: true },
  },
  components: {
    DictionariesSelect,
  },
  name: "manageDetail",
  dicts: [
    "energy_family_splitting_type", // 分户类别
    "energy_subarea_type", // 分区类别
    "energy_subarea_child_type", // 分区子类
    "energy_type", // 分类类别-能耗类型
    "subentry_type", // 分项类别
    "energy_andnorgate", // 逻辑关系
  ],
  data() {
    return {
      live2Codes: [],
      form: {
        energyType: null,
        classifyType: null, // 参数管理类型
        itemType: null,
        subitemType: null, // 分区子类
        list: [],
        measureAlone: 1, // 是否单独计量
        // date: null,
        // people: "",
      },
      rules: {
        energyType: [
          {
            required: true,
            message: "所属能耗类型不能为空",
            trigger: ["blur", "change"],
          },
        ],
        itemType: [
          {
            required: true,
            message: "类别不能为空",
            trigger: ["blur", "change"],
          },
        ],
        subitemType: [
          {
            required: true,
            message: "子类不能为空",
            trigger: ["blur", "change"],
          },
        ],
        list: [
          {
            required: true,
            message: "规则不能为空",
            trigger: ["blur", "change"],
          },
        ],
        measureAlone: [
          {
            required: true,
            message: "请选择是否",
            trigger: ["blur", "change"],
          },
        ],
        // date: [{ required: true, message: "时间不能为空", trigger: "blur" }],
        relation: [
          {
            required: true,
            message: "关系不能为空",
            trigger: ["blur", "change"],
          },
        ],
        ruleId: [
          {
            required: true,
            message: "规则不能为空",
            trigger: ["blur", "change"],
          },
        ],
      },
      pickerOptions: {
        disabledDate: (time) => {
          // 禁用今天之后的日期(不包含今天)
          return time.getTime() > Date.now();
          //   // 禁用今天之后的日期(包含今天)
          // return time.getTime() > Date.now() - 8.64e7;
        },
      },
      rowObj: {
        relation: null, // 关系 0 and 1 or
        ruleId: null, // 规则
      },
      rulesArr: [],
      way: 0, // 0 新增 1修改
      tabName: "",
      dictArr: null, // 字典数组
      dictArr2: null, // 分区子类
    };
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.$refs?.["detailform"]?.clearValidate();
          this.typeJudge();
        }
      },
      deep: false,
      immediate: false,
    },
  },
  methods: {
    getTypeAndLabelLv2Code(val, flag) {
      let dict =
        this.waytype == 4
          ? "subentry_type"
          : this.waytype == 2
          ? "energy_subarea_child_type"
          : "";
      let data =
        this.waytype == 4
          ? this.dict.type.energy_type.find((item) => item.value == val)
          : this.waytype == 2
          ? this.dict.type.energy_subarea_type.find((item) => item.value == val)
          : {};
      if (Object.keys(data).length > 0) {
        typeAndLabelLv2Code(dict, data.raw.dictCode).then((response) => {
          this.live2Codes = response.data;
          if (this.waytype == 4 && flag != 1) {
            this.form.itemType = "";
          }
          this.resetTable();
        });
      }
    },
    // 类型判断（新增or修改）
    typeJudge() {
      if (this.id == "") {
        this.way = 0;
      } else {
        this.way = 1;
        this.requestDetail();
      }
      this.form.classifyType = this.waytype;
      switch (this.waytype) {
        case "1":
          this.tabName = "分户";
          this.dictArr = this.dict.type.energy_family_splitting_type;
          break;
        case "2":
          this.tabName = "分区";
          this.dictArr = this.dict.type.energy_subarea_type;
          this.dictArr2 = this.dict.type.energy_subarea_child_type;
          break;
        case "3":
          this.tabName = "分类";
          this.dictArr = this.dict.type.energy_type;
          break;
        case "4":
          this.tabName = "分项";
          this.dictArr = this.dict.type.subentry_type;
          break;
      }
    },
    // 请求详情
    requestDetail() {
      let id = this.id;
      getDetail(id)
        .then((res) => {
          // console.log(res, "detail");
          if (res.code === 700) {
            that.$message.warning(res.msg);
            return false;
          }
          let data = res?.data ?? {};
          this.detailDel(data);
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!20081");
        });
    },
    // 详情数据处理
    detailDel(data) {
      this.form.id = data?.id ?? null;
      this.form.measureAlone = data?.measureAlone ?? 1;
      this.getTypeAndLabelLv2Code(data.itemType, 1);
      if (this.waytype == 4) {
        this.form.energyType = data.itemType;
        this.form.itemType = data.subitemType;
      } else {
        this.form.itemType = data?.itemType ?? null;
        this.form.subitemType = data?.subitemType ?? null;
      }
      this.requestRuleslist();
      setTimeout(() => {
        this.form.list = data?.ruleVos ?? [];
      }, 500);
    },
    handleSelect(val, flage) {
      this.form[flage] = val;
      if (flage != "subitemType") {
        this.resetTable();
        setTimeout(() => {
          if (String(val).length > 0) this.requestRuleslist();
        }, 100);
      }
      if (this.waytype == 4) {
        return false;
      }
      if (this.waytype == 2) {
        if (flage == "itemType") {
          this.getTypeAndLabelLv2Code(val, 1);
          this.form.subitemType = null;
        }
      }

      // console.log(flage, val);
    },
    handleClear(flage) {
      this.form[flage] = null;
      if (flage != "subitemType") {
        this.resetTable();
      }
    },
    // 划分规则选择事件
    handleChange(val, indexs) {
      // console.log(val, indexs);
      // this.rulesArrdelect(val, indexs);
    },
    // 分户规则列表清空
    resetTable() {
      this.form.list = [];
    },
    // 请求划分规则集合
    requestRuleslist() {
      let params = {
        classifyType: this.form.classifyType,
        itemType: this.form.itemType,
      };
      getRuleslist(params)
        .then((res) => {
          console.log(res, "规则模板集合");
          if (res.code === 700) {
            that.$message.warning(res.msg);
            return false;
          }
          this.rulesArr = res?.data ?? [];
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!20082");
        });
    },
    // 新增一行
    handleAddrow() {
      if (this.rulesArr.length == 0) {
        this.$message({
          message: "请先选择类别",
          type: "warning",
        });
      } else {
        if (this.form.list.length < this.rulesArr.length) {
          this.form.list.push(deepClone(this.rowObj));
        } else {
          this.$message({
            message: "最多只可添加划分规则数量的" + this.tabName + "规则数",
            type: "warning",
          });
        }
      }
    },
    handleDelete(row) {
      const index = this.form.list.indexOf(row);
      this.form.list.splice(index, 1);
    },
    // 表单参数处理
    formparamsDeal(form) {
      let params = {};
      params = { ...form };
      params.list.map((item) => {
        this.rulesArr.map((tig) => {
          if (item.ruleId == tig.ruleId) {
            item.ruleContent = tig.ruleContent;
          }
        });
      });
      params.rules = params.list;
      params.list = null;
      if (this.way == 0) {
        // 新增
      } else if (this.way == 1) {
        // 修改
      }
      if (this.waytype == 4) {
        params.subitemType = params.itemType;
        params.itemType = params.energyType;
      }
      return params;
    },
    // 规则重复性校验
    rulesRepet() {
      let flag = true;
      let arr = this.form.list;
      let num = 0;
      arr.map((item) => {
        if (item.relation == null) {
          num++;
        }
        if (item.ruleId == null) {
          num++;
        }
      });
      const newListLength = new Set(arr.map((item) => item.ruleId)).size;
      const listLength = arr.length;
      if (listLength > newListLength) {
        // console.log("重复");
        num++;
      }
      if (num != 0) {
        flag = false;
      }
      return flag;
    },
    // 确定
    handleConfirm() {
      const flag = this.rulesRepet();
      if (flag) {
        let params = this.formparamsDeal(this.form);
        // console.log(params, "111");
        this.$refs["detailform"].validate((valid) => {
          if (valid) {
            let requestWay = null;
            let successMsg = "";
            let errcode = "";
            switch (this.way) {
              case 0:
                // 新增
                requestWay = postSub;
                successMsg = "新增成功";
                errcode = "20083";
                break;
              case 1:
                // 修改
                requestWay = putSub;
                successMsg = "修改成功";
                errcode = "20085";
                break;
            }
            requestWay(params)
              .then((res) => {
                // console.log(res);
                if (res.code === 700) {
                  that.$message.warning(res.msg);
                  return false;
                }
                this.$message({
                  type: "success",
                  message: successMsg,
                });
                this.handleClose(true);
              })
              .catch((err) => {
                // this.$message.error("系统错误,请联系管理员!" + errcode);
              });
          }
        });
      } else {
        this.$message({
          message: "添加的规则有重复，请确认",
          type: "warning",
        });
      }
    },
    resetForm() {
      this.form = {
        classifyType: null,
        itemType: null,
        energyType: null,
        subitemType: null,
        list: [],
        measureAlone: 1,
        // date: null,
        // people: "",
      };
      this.$refs["detailform"].clearValidate();
    },
    // 取消关闭
    handleClose(status) {
      this.resetForm();
      this.way = 0;
      this.dictArr = null;
      this.dictArr2 - null;
      this.tabName = "";
      this.rulesArr = [];
      // this.$emit("update:visible", false);
      this.$emit("close", typeof status === "boolean" ? status : false);
    },
  },
};
</script>

<style lang="scss" scoped>
.cellCenter {
  margin-top: 15px;
}
</style>
